package com.example.memoapp.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.memoapp.R;
import com.example.memoapp.database.MemoDatabaseHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AddMemoActivity extends AppCompatActivity {

    private EditText etTitle, etContent;
    private MemoDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_memo);

        etTitle = findViewById(R.id.et_memo_title);
        etContent = findViewById(R.id.et_memo_content);
        Button btnSave = findViewById(R.id.btn_save_memo);

        dbHelper = new MemoDatabaseHelper(this);

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveMemo();
            }
        });
    }

    private void saveMemo() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();

        if (title.isEmpty()) {
            Toast.makeText(this, "标题不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());

        long result = dbHelper.addMemo(title, content, date);

        if (result != -1) {
            Toast.makeText(this, "备忘录保存成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(AddMemoActivity.this, MainActivity.class);
            startActivity(intent);
        } else {
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        }
    }
}    